/**
 *  Eclipse Public License 1.0
 */
package org.fireblade.easysms;

import java.io.BufferedWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Service;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

/**
 * Action for getting the html page for one conversation
 */
public class HttpActionShowThread {
  /**
   * own log tag
   */
  private static final String LOGTAG = MainActivity.EASY_SMS + HttpActionShowThread.class.getSimpleName();


  /**
   * @param values
   * @param writer
   * @param service the context/service
   * @throws Exception
   */
  public static void process(Service service, Map<String, String> values, BufferedWriter writer)
    throws Exception {
    boolean uniqueContact = !(values.get("different") != null && values.get("different").equals("true"));
    boolean full = values.get("full") != null;
    writer
      .write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\r\nhttp://www.w3.org/TR/html4/strict.dtd>\r\n"
        + "<html><head>"
        + "<link rel=\"stylesheet\" href=\"/style.css\" type=\"text/css\" media=\"screen\" />"
        + "<META HTTP-EQUIV=\"content-type\" CONTENT=\"text/html; charset=utf-8\"></head><body  bgcolor=\"#DDDDDD\">"
        + "<div id=\"r1\" style=\"position: fixed; top:0; right:0; height: 18px; width: 55px; font-size:1em; background-color: #CCCCCC; text-align: right; \">"
        + "<small><a href=\"/showthread?id="
        + (values.get("id") != null ? (values.get("id") + (uniqueContact ? "" : "&different=true")) : "")
        + "\">Update</a></small></div>");

    String id = values.get("id");
    if (null != values.get("id")) {
      if (null != values.get("address") && null != values.get("text")) {
        if (null != values.get("draftid")) {
          String draftID = values.get("draftid");
          if ("".equals(draftID) || 0 == Integer.parseInt(draftID)) {
            Log.d(LOGTAG, "Save new message as draft");
            MessageHelper.saveDraft(service, 0, Integer.parseInt(id), values.get("text"));
          } else {
            if (null != values.get("action") && values.get("action").equals("savedraft")) {
              Log.d(LOGTAG, "Update message as draft");
              MessageHelper.saveDraft(service, Integer.parseInt(values.get("draftid")), Integer.parseInt(id),
                values.get("text"));
            } else {
              Log.d(LOGTAG, "Send draft");
              MessageHelper.sendDraft(service, values.get("draftid"), URLDecoder.decode(values.get("address")),
                values.get("text"));
            }
          }
        } else {
          System.out.println("TEXT: *" + values.get("text") + "*");
          MessageHelper.sendSMS(service, new String[] { URLDecoder.decode(values.get("address")) }, values
            .get("text"), Integer.parseInt(id));
        }
      }
      if (null != values.get("mid")) {
        String action = values.get("action");
        if (null != action) {
          if (action.equals("senddraft")) {
            if (values.get("address") != null) {
              MessageHelper
                .sendDraft(service, values.get("mid"), URLDecoder.decode(values.get("address")), null);
            }
          } else if (action.equals("toogleRead")) {
            if (values.get("read") != null) {
              MessageHelper.toogleRead(service, values.get("mid"), Integer.parseInt(values.get("read")));
            }
          } else if (action.equals("deleteMessage")) {
            MessageHelper.deleteMessage(service, values.get("mid"));
          } else if (action.equals("retry")) {
            MessageHelper.retry(service, values.get("mid"));
          } else {
            Log.w(LOGTAG, "Unknown action: " + action);
          }
        }
      }
      writeThread(service, writer, id, uniqueContact, full, id);
    }
    writer.write("</body></html>");
  }


  /**
   * @param writer
   */
  private static void writeThread(Service service, BufferedWriter writer, String threadId,
    boolean uniqueContact, boolean full, String id) throws Exception {
  
    int person = 0;
    boolean draft = false;
    String address = null;
    String name = "?";
    List<Message> elements = new ArrayList<Message>();
    int resultCount = cursor.getCount();

    Log.d(LOGTAG, "Show thread " + threadId + " with " + resultCount + " messages, unique? " + uniqueContact);
    boolean hasOlderMessages = false;
    if (resultCount == 0) {
      writer.write("<br/>");
      String showAll = service.getResources().getString(R.string.thread_deleted);
      writer.write("<center><b>" + showAll + "</b></center>");
      writer.write("<br/>");
    } else {
      if (resultCount == 1 && cursor.moveToNext() && cursor.getInt(5) == 3) {
        // thread has only one draft message
        Log.d(LOGTAG, "Thread is a draft only thread");
        Message element = new Message();
  
        String[] result = Util.getNameAndAddressAndPersonByThread(service, threadId);
        element.address = result[1];
        element.name = result[0];
        name = element.name;
        address = element.address;
        if (null != address) {
          address = address.trim();
        }
        person = Integer.parseInt(result[2]);

      } else {
        Log.d(LOGTAG, "Thread is a normal thread.");
        boolean isFirst = true;
        while (isFirst && cursor.moveToFirst() || cursor.moveToNext()
          && (full || (!full && elements.size() <= 20))) {
          isFirst = false;
          Message element = new Message();
          elements.add(element);
          element.address = cursor.getString(0);
          if (person == 0) {
            person = cursor.getInt(1);
          }
          if (null == address) {
            address = element.address;
            if (null != address) {
              address = address.trim();
            }
          }
          element.date = cursor.getLong(2);
          element.isRead = cursor.getInt(3) == 1 ? true : false;
          element.status = cursor.getInt(4);
          element.type = cursor.getInt(5);
          if (element.type == 3) {
            draft = true;
          }
          element.body = cursor.getString(6);
          element.id = cursor.getInt(7);
          Log.d(LOGTAG, " adding message " + element.body);
        }

        if (cursor.moveToNext()) {
          hasOlderMessages = true;
        }
        cursor.close();

        if (uniqueContact) {
          if (person != 0) {
            name = Util.getNameByContactId(person, service);
          } else {
            String[] result = Util.getNameAndAddressAndPersonByThread(service, threadId);
            name = result[0];
            address = result[1];
          }
          for (Message t : elements) {
            t.name = name;
          }

        } else {
          for (Message t : elements) {
            if (null != t.address) {
              t.name = Util.getNameAndContactByNumber(t.address, service)[0];
            } else {
              t.name = "?";
            }
          }
        }
      }
      Util.writeScript(service, writer, draft);
      writer.write("<table width=\"100%\">");
      writeSendForm(service, writer, uniqueContact, name, address, threadId, draft);
      for (Message t : elements) {
        writeMessage(service, writer, t, uniqueContact, threadId, address);
      }
      writer.write("</table>");
      if (hasOlderMessages) {
        writer.write("<br/>");
        String showAll = service.getResources().getString(R.string.thread_showall);
        writer.write("<center><b><a href=\"/showthread?id=" + id + "&full=true\">" + showAll
          + "</a></b></center>");
        writer.write("<br/>");
      }
    }
  }


  /**
   * @param service
   * @param writer
   * @param uniqueContact
   */
  private static void writeSendForm(Service service, BufferedWriter writer, boolean uniqueContact, String name,
    String address, String threadId, boolean draft) throws Exception {
    writer.write("<tr><td>");
    if (uniqueContact) {
      writer.write("<table border=0 hspacing=0 vspacing=0>");
      if (!MainActivity.DONATE_VERSION) {
        writer.write("<tr><td>" + service.getResources().getString(R.string.donate_long_sms_support)
          + "</td></tr>");
      }
      writer.write("<tr><td>" + service.getResources().getString(R.string.thread_recipient) + ": <b>" + name
        + "</b> [" + address
        + "]</td><td width=\"120\" align=\"left\"><span id=\"leftchars\" name=\"leftchars\">160"
        + "</span>/<span id=\"smscount\" name=\"smscount\">1</span> (<span id=\"leftTotal\" name=\"leftTotal\">"
        + Util.MAX_SMS_CHARS + "</span>)</td></tr>");
      writer.write("<tr><td colspan=2>");
      writer.write("<form name=\"sendform\" method=\"GET\" action=\"/showthread\">");
      writer.write("<input type=\"hidden\" name=\"id\" value=\"" + threadId + "\"/>");
      writer.write("<input type=\"hidden\" name=\"draftid\" value=\"\"/>");
      writer.write("<input type=\"hidden\" name=\"action\" value=\"\"/>");
      writer.write("<input type=\"hidden\" name=\"address\" value=\"" + URLEncoder.encode(address) + "\"/>");
      writer.write("<textarea  onkeyup=\"updateCharCounter();\" cols=\"70\" rows=\"5\" name=\"text\">");
      writer.write("</textarea><br/>");
      writer.write("<input onClick=\"return checkContent();\" type=\"submit\" name=\"senden\" value=\""
        + service.getResources().getString(R.string.thread_action_send) + "\"/>");
      writer.write("<input "
        + (draft ? "disabled" : "")
        + " onClick=\"checkContent() && saveDraft()\" type=\"button\" name=\"entwurf\" value=\""
        + (draft ? service.getResources().getString(R.string.thread_draft_available) : service.getResources()
          .getString(R.string.thread_save_draft)) + "\"/>");
      writer.write("<input onClick=\"clearContent()\" type=\"button\" name=\"leeren\" value=\""
        + service.getResources().getString(R.string.thread_clear) + "\"/>");
      writer.write("</form></td></tr></table>");
    } else {
      writer.write(service.getResources().getString(R.string.thread_no_anwser));
    }
    writer.write("</td></tr>");

  }


  protected static void writeMessage(Service service, BufferedWriter writer, Message message,
    boolean uniqueContact, String threadId, String address) throws Exception {
    writer.write("<tr " + (message.isRead ? "bgcolor=\"#EEEEEE\"" : "bgcolor=\"#CCCCFF\"") + "><td>");
    writer.write("<table width=\"100%\"><tr><td width=\"120\"><b>");
    if (message.type == 1) {
      writer.write(message.name + ":");
    } else {
      if (uniqueContact) {
        writer.write(service.getResources().getString(R.string.thread_me) + ":");
      } else {
        writer.write(service.getResources().getString(R.string.thread_me_to) + " " + message.name + " ["
          + message.address + "]:");
      }
    }
    writer.write("</b></td><td halign=\"top\" rowspan=\"3\">");
    message.body = message.body.replace("<", "&lt;");
    message.body = message.body.replace(">", "&gt;");
    message.body = message.body.replace("\r\n", "<br/>");
    message.body = message.body.replace("\r", "<br/>");
    message.body = message.body.replace("\n", "<br/>");
    writer.write(message.body);
    message.body = message.body.replace("<br/>", "<br>");
    writer.write("</td><td width=\"3\" bgcolor=\"#CCCCCC\" rowspan=\"3\"><a onClick=\"return confirm('"
      + service.getResources().getString(R.string.thread_del_message) + "?')\" href=\"/showthread?id="
      + threadId + "&action=deleteMessage&mid=" + message.id + "\">D E L</a></td></tr><tr><td>");
    writer.write(Util.format(service, message.date));
    writer.write("</td></tr><tr><td>");
    if (message.status != -1) {
      if (message.status == 0) {
        writer.write("<font color=\"#00CC00\">"
          + service.getResources().getString(R.string.thread_state_delivered) + "</font>");
      } else if (message.status == 64) {
        if (message.type == 2) {
          writer.write("<font color=\"#0000FF\">"
            + service.getResources().getString(R.string.thread_state_wait_report) + "</font>");
        } else if (message.type == 5) {
          writer.write("<font color=\"#FF0000\">"
            + service.getResources().getString(R.string.thread_state_error)
            + "</font>&nbsp;<a href=\"/showthread?id=" + threadId + "&action=retry&mid=" + message.id + "\">"
            + service.getResources().getString(R.string.thread_action_retry) + "</a>");
        } else if (message.type == 6) {
          writer.write("<font color=\"#0000FF\">"
            + service.getResources().getString(R.string.thread_state_queued) + "...</font>");
        } else if (message.type == 4) {
          writer.write("<font color=\"#0000FF\">"
            + service.getResources().getString(R.string.thread_state_outgoing) + "...</font>");
        } else {
          writer.write("<font color=\"#FF0000\">"
            + service.getResources().getString(R.string.thread_state_sent_unknown) + "</font>");
        }
      } else {
        writer.write(message.status + "/" + message.type);
      }
      writer.write("");
    } else if (message.type == 2) {
      writer.write("<font color=\"#00CC00\">" + service.getResources().getString(R.string.thread_state_sent)
        + "</font>");
    } else if (message.type == 3) {
      writer.write("<font color=\"#0000FF\">" + service.getResources().getString(R.string.thread_state_draft)
        + "</font><br/><a href=\"/showthread?id=" + threadId + "&action=senddraft&mid=" + message.id
        + "&address=" + URLEncoder.encode(address) + "\">"
        + service.getResources().getString(R.string.thread_action_send) + "</a>");
      writer.write("<a href=\"/showthread?\" onClick=\"editDraft(" + message.id + ",'"
        + message.body.replace("\"", "'").replace("'", "\\'") + "'); return false;\">"
        + service.getResources().getString(R.string.thread_action_modify) + "</a>");
    } else if (message.type == 5) {
      writer.write("<font color=\"#FF0000\">" + service.getResources().getString(R.string.thread_state_error)
        + "</font>&nbsp;<a href=\"/showthread?id=" + threadId + "&action=retry&mid=" + message.id + "\">"
        + service.getResources().getString(R.string.thread_action_retry) + "</a>");
    } else if (message.type == 4) {
      writer.write("<font color=\"#0000FF\">" + service.getResources().getString(R.string.thread_state_outgoing)
        + "...</font>");
    } else if (message.type == 1) {
      writer.write("<a href=\"/showthread?id="
        + threadId
        + "&action=toogleRead&read="
        + (message.isRead ? "0" : "1")
        + "&mid="
        + message.id
        + "\">"
        + (message.isRead ? service.getResources().getString(R.string.thread_action_as_unread) : service
          .getResources().getString(R.string.thread_action_as_read)) + "</a>");
    } else if (message.type == 6) {
      writer.write("<font color=\"#0000FF\">" + service.getResources().getString(R.string.thread_state_queued)
        + "...</font>");
    } else {
      writer.write(message.status + "+" + message.type);
    }
    writer.write("</td></tr></table></td></tr>");
    writer.flush();
  }
}
